import 'package:flutter/material.dart';
import 'package:im_app/demo/page/footer_underscroll.dart';
import 'package:refresh_loadmore/refresh_loadmore.dart';

class LoadMorePage extends StatefulWidget {
  LoadMorePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _LoadMorePageState createState() => _LoadMorePageState();
}

class _LoadMorePageState extends State<LoadMorePage> {
  /// is the last page | 是否为最后一页
  bool isLastPage = false;

  List? list;
  int page = 1;
  int nextIndex = 1;
  int preIndex = 1000;

  @override
  void initState() {
    super.initState();
    loadFirstData();
  }

  Future<void> loadFirstData() async {
    await Future.delayed(Duration(seconds: 1), () {
      setState(() {
        list = [
          'dddd',
          'sdfasfa',
          'sdfgaf',
          'adsgafg',
          'dddd',
          'sdfasfa',
          'sdfgaf',
          'adsgafg',
          'dddd',
          'sdfasfa',
          'sdfgaf',
          'adsgafg'
              'adsgafg',
          'dddd',
          'sdfasfa',
          'sdfgaf',
          'adsgafg'
        ];
        isLastPage = false;
        page = 1;
      });
    });
  }

  Future<void> loadRefresh() async {
    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        for (var i=0; i<5; i++) {
          var t = preIndex--;
          list?.insert(0, t.toString());
        }
        
        isLastPage = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: list != null
          ? RefreshLoadmore(
        onRefresh:  () async => await loadRefresh(),
        onLoadmore: () async {
          await Future.delayed(Duration(seconds: 3), () {
            setState(() {
              for (var i=0; i<20; i++) {
                var t = nextIndex++;
                list?.add(t.toString());
              }
              page++;
            });
          });
        },
        noMoreWidget: Text(
          'No more data, you are at the end',
          style: TextStyle(
            fontSize: 18,
            color: Theme.of(context).disabledColor,
          ),
        ),
        loadingWidget: Text('loading........'),
        isLastPage: isLastPage,
        child: list!.isNotEmpty
            ? Column(
          children: list!
              .map(
                (e) => ListTile(
              title: Item(title: e),
              trailing: Icon(Icons.accessibility_new),
            ),
          )
              .toList(),
        )
            : Center(
          child: Text('empty'),
        ),
      )
          : Center(child: CircularProgressIndicator()),
    );
  }
}